import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    nickName: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_NICKNAME: (state, nickName) => {
    state.nickName = nickName
  }
}

const actions = {
  // user login  组件中可以调用这个异步动作 eg：this.$store.dispatch('user/login')  user 属于user模块的命名空间
  login({
    commit
  }, userInfo) {
    const {
      userName,
      password
    } = userInfo
    // pending 进行中 rejected 已失败  fulfilled 已成功  resolved 已定型（已完成）
    return new Promise((resolve, reject) => {
      login({
        userName: userName.trim(),
        password: password
      }).then(response => {
        const data = response
        console.log(data.content)
        commit('SET_TOKEN', data.content)
        setToken(data.content)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response
        // console.log(data)

        if (!data) {
          reject('获取用户信息失败,请重新登录.')
        }
        // 字段参数要和后台实体类队形
        // const { userName, headPic } = data.content

        console.log('role：' + data.content.roleSign)
        let roles = new Array()
        roles.push(data.content.roleSign)

        commit('SET_NAME', data.content.userName)
        // console.log(data.content.nickName)
        commit('SET_NICKNAME', data.content.nickName)
        commit('SET_ROLES', roles)
        commit('SET_AVATAR', data.content.headPic)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
